// pages/pay/index.js
import wxApi from '../../utils/wxApi'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getshopcartlist: [],
    num: 0,
    price: 0,
    adddata: {},
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取收获地址
    let adddata = wx.getStorageSync('adddata')
    console.log('收获地址', adddata);
    this.setData({
      adddata
    })
    console.log(this.data.adddata);
    //本地拿数据
    let getshopcartlist = wx.getStorageSync('cartdata') || []
    let num = 0
    let price = 0
    getshopcartlist.forEach(item => {
      num += item.num
      price += item.goods_price * item.num
    })
    this.setData({
      getshopcartlist,
      num,
      price
    })


  },

  //点击跳转支付页面
  clickpay: async function () {
    try {
      //获取token
      let token = wx.getStorageSync('token')
      //如果没有token就跳转授权页面
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        })
      }
      //如果存在就就创建订单
      let goods = []
      this.data.getshopcartlist.forEach(item => {
        goods.push({
          goods_id: item.goods_id,
          goods_number: item.goods_number,
          goods_price: item.goods_price
        })
      })
      let sendData = {
        order_price: this.data.totalPrice,
        consignee_addr: this.data.adddata.all,
        goods: goods
      }
      let orderInfo = await wx.wx.myApi.createOrder(sendData)

      //获取订单id成功
      let {
        order_number
      } = orderInfo.data.message;
      //通过发送订单id到服务器, 服务器后台获取微信预支付参数
      let payInfo = await wx.myApi.reqUnifiedorder({
        order_number
      });
      let {
        pay
      } = payInfo.data.message;
      let checkOrder = await wx.myApi.checkOrder({
        order_number
      });
      console.log("订单状态", checkOrder)
      if (checkOrder) { //清空购物车已经支付的信息,跳转到查看订单页面
        let cart = wx.getStorageSync('cart');
        cart = cart.filter(item => !item.checked)
        wx.setStorageSync('cart', cart);
        //跳转到查看订单界面
        wx.navigateTo({
          url: '/pages/order/index',
        })
      }
    } catch (err) { //异常捕获
      console.log("支付异常", err);
      await wxApi.showToast("支付失败")
    }

  }

})